package cn.yup.service.impl;

import cn.yup.domain.Employee;
import cn.yup.domain.Permission;
import cn.yup.exception.MyException;
import cn.yup.mapper.EmployeeMapper;
import cn.yup.mapper.PermissionMapper;
import cn.yup.query.EmployeeQueryObject;
import cn.yup.service.IEmployeeService;
import cn.yup.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public PageInfo findAll(EmployeeQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Employee> list = employeeMapper.selectByCondition(qo);

        return new PageInfo(list);
    }

    @Override
    public void deleteById(Long id) {

        int result = employeeMapper.deleteById(id);
        if(result == 0){
            throw new MyException("删除失败");
        }

    }

    @Override
    public Employee findById(Long id) {
        return employeeMapper.findById(id);
    }


    @Override
    public void saveOrUpdate(Employee employee ,Long[] ids) {
        if (employee.getId() != null) {
            employeeMapper.deleteRelation(employee.getId());
            employeeMapper.updateById(employee);
        }
        else {

            employeeMapper.insert(employee);
        }
        if(ids != null) {
            for (Long id : ids) {
                employeeMapper.insertRelation(employee.getId(), id);
            }
        }
    }

    @Override
    public Employee login(String username, String password) {

        Employee employee = employeeMapper.selectEmpByUsernameAndPassword(username,password);
        if(employee == null){
            throw new MyException("登录失败，请稍后重试");
        }

        if (employee != null) {
            UserContext.setCurrentUser(employee);
            List<Permission> list = permissionMapper.selectPermissionByEmpId(employee.getId());
            UserContext.setCurrentEmpPermission(list);
        }
        return employee;
    }

    @Override
    public List<Employee> listAll() {
        return employeeMapper.listAll();
    }


}

